import React, { useState, useEffect } from 'react';
import * as tf from '@tensorflow/tfjs';
import { preprocessData } from '../../utils/dataPreprocessor';
import './Predictor.css';

function Predictor({ model, data, trainingHistory }) {
  const [sequence, setSequence] = useState([]);
  const [predictions, setPredictions] = useState([]);
  const [historyChart, setHistoryChart] = useState(null);
  const [isPredicting, setIsPredicting] = useState(false);

  useEffect(() => {
    if (data && data.length > 0) {
      const initialSequence = data.slice(-10);
      setSequence(initialSequence);
    }
  }, [data]);

  useEffect(() => {
    if (trainingHistory) {
      // Create a simple chart of training history
      const chartData = {
        labels: Array.from({ length: trainingHistory.epoch.length }, (_, i) => i + 1),
        datasets: [
          {
            label: 'Training Accuracy',
            data: trainingHistory.acc,
            borderColor: '#2196F3',
            fill: false
          },
          {
            label: 'Validation Accuracy',
            data: trainingHistory.val_acc,
            borderColor: '#4CAF50',
            fill: false
          }
        ]
      };
      
      setHistoryChart({
        data: chartData,
        options: {
          responsive: true,
          scales: {
            y: {
              beginAtZero: true,
              max: 1
            }
          }
        }
      });
    }
  }, [trainingHistory]);

  const handlePredict = async () => {
    if (!model || !sequence.length) return;
    
    setIsPredicting(true);
    
    try {
      // Prepare input sequence
      const inputSequence = sequence.slice(-model.input.shape[1]);
      const inputTensor = tf.tensor2d([inputSequence], [1, inputSequence.length]);
      
      // Make prediction
      const prediction = model.predict(inputTensor);
      const predictionData = await prediction.data();
      
      // Format predictions with probabilities
      const formattedPredictions = Array.from(predictionData)
        .map((prob, num) => ({
          number: num,
          probability: prob,
          percentage: (prob * 100).toFixed(2) + '%'
        }))
        .sort((a, b) => b.probability - a.probability);
      
      setPredictions(formattedPredictions);
    } catch (error) {
      console.error('Prediction error:', error);
    } finally {
      setIsPredicting(false);
    }
  };

  const addToSequence = (num) => {
    setSequence(prev => [...prev, num].slice(-20)); // Keep last 20 numbers
  };

  const clearSequence = () => {
    setSequence([]);
    setPredictions([]);
  };

  const getTop6Accuracy = () => {
    if (!predictions.length || !sequence.length) return 'N/A';
    
    const nextNumber = sequence[sequence.length - 1];
    const top6 = predictions.slice(0, 6).map(p => p.number);
    
    return top6.includes(nextNumber) ? '✅ Correct' : '❌ Incorrect';
  };

  return (
    <div className="card">
      <h2>Predictor</h2>
      
      <div className="sequence-container">
        <h3>Current Sequence</h3>
        <div className="sequence-display">
          {sequence.length > 0 ? sequence.join(', ') : 'No sequence yet'}
        </div>
        
        <div className="number-pad">
          {[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(num => (
            <button 
              key={num} 
              className="number-button" 
              onClick={() => addToSequence(num)}
            >
              {num}
            </button>
          ))}
        </div>
        
        <div className="sequence-controls">
          <button 
            className="button" 
            onClick={handlePredict}
            disabled={!sequence.length || isPredicting}
          >
            {isPredicting ? 'Predicting...' : 'Predict Next Number'}
          </button>
          
          <button 
            className="button button-clear" 
            onClick={clearSequence}
          >
            Clear Sequence
          </button>
        </div>
      </div>
      
      {predictions.length > 0 && (
        <div className="predictions-container">
          <h3>Predictions (Top 6 Accuracy: {getTop6Accuracy()})</h3>
          
          <div className="table-container">
            <table>
              <thead>
                <tr>
                  <th>Number</th>
                  <th>Probability</th>
                  <th>Percentage</th>
                </tr>
              </thead>
              <tbody>
                {predictions.map((pred, index) => (
                  <tr key={pred.number} className={index < 6 ? 'top-6' : ''}>
                    <td>{pred.number}</td>
                    <td>{pred.probability.toFixed(6)}</td>
                    <td>{pred.percentage}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          
          <div className="prediction-bars">
            {predictions.slice(0, 6).map(pred => (
              <div key={pred.number} className="bar-container">
                <div className="bar-label">{pred.number}</div>
                <div 
                  className="bar" 
                  style={{ width: `${pred.probability * 100}%` }}
                >
                  <span className="bar-text">{pred.percentage}</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
      
      {historyChart && (
        <div className="history-chart">
          <h3>Training History</h3>
          <div className="chart-container">
            {/* In a real app, you would use a charting library like Chart.js here */}
            <div className="chart-placeholder">
              <p>Accuracy over epochs:</p>
              <p>Training: {historyChart.data.datasets[0].data.slice(-1)[0].toFixed(4)}</p>
              <p>Validation: {historyChart.data.datasets[1].data.slice(-1)[0].toFixed(4)}</p>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

export default Predictor;